<template>
  <el-upload
    :multiple="multiple"
    :on-success="handleUploadSuccess"
    list-type="picture-card"
    class="image-uploader"
    :action="uploadUrl"
    :headers="headers"
    :before-upload="beforeUpload"
    :on-remove="removeFile"
    :file-list="fileList"
  >
    <i class="el-icon-upload"/>
  </el-upload>
</template>

<script>
import { getToken } from "@/utils/auth";
import { inArray, removeValInArray } from "@/utils/util";
import { QiniuBaseUrl } from "@/settings";

export default {
  name: "UploadImage",
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "upload/upload",
      headers: {
        "X-Token": getToken()
      },
      limitTypes: ["image/jpeg", "image/png"],
      limitSize: 10 * 1024 * 1024,
      fileList: []
    };
  },
  watch: {
    value: function(val) {
      if (val == "" || val == null) {
        this.fileList = [];
      } else {
        let tmp = val.split(",")
        this.fileList = this.fileList.filter(item => {
          return inArray(item.response.url, tmp);
        });
        let fileList = this.fileList;

        for (let i = 0; i < tmp.length; ++i) {
          let find = false;
          for (let j = 0; j < fileList.length; ++j) {
            if (fileList[j].response.url == tmp[i]) {
              find = true;
              break;
            }
          }
          if (!find) {
            fileList.push({
              name: tmp[i],
              url: QiniuBaseUrl + tmp[i],
              response: {
                url: tmp[i]
              }
            });
          }
        }
      }
    }
  },
  methods: {
    removeFile(res) {
      let url = res.response.url;
      let tmp = this.value.split(",");
      removeValInArray(url, tmp);
      for (var i = 0; i < this.fileList.length; ++i) {
        if (url == this.fileList[i].response.url) {
          this.fileList.splice(i, 1);
          break;
        }
      }
      this.$emit("input", tmp.join(","));
    },
    handleUploadSuccess(res, file) {
      if (res.code === 20000) {
        let tmp =
          this.value == "" || this.value == null ? [] : this.value.split(",");
        let newVal = tmp.concat(res.url);
        this.fileList.push(file);
        this.$emit("input", newVal.join(","));
      }
    },
    beforeUpload(file) {
      if (!inArray(file.type, this.limitTypes)) {
        this.$message.error("上传图片格式不支持");
        return false;
      }
      if (file.size > this.limitSize) {
        this.$message.error("上传图片大小不能超过 10MB!");
        return false;
      }
      return true;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.sg-preview-image {
  width: 148px;
  height: 148px;
}
.sg-upload-container {
  display: flex;
}
</style>
